package ch12;

class ThreadEx15 {
	public static void main(String args[]) {
		Runnable r = new RunnableEx15();
		Thread t1 = new Thread(r);
		Thread t2 = new Thread(r);

		t1.start();
		t2.start();
	}
}

class Account {
	int balance = 1000;

	public void withdraw(int money){ //[1]
	// public synchronized void withdraw(int money){ //[2]	
		if(balance >= money) {
			try { Thread.sleep(1000);} catch(Exception e) {}
			balance -= money;
		}
	}
}

class RunnableEx15 implements Runnable {
	Account account = new Account();

	public void run() {
		while(account.balance > 0) {			
			int money = (int)(Math.random() * 3 + 1) * 100;
			account.withdraw(money);
			System.out.println("balance:"+account.balance);
		}
	}
}
/* no synchronized:
balance:700
balance:700
balance:100
balance:100
balance:100
balance:100
balance:-100
balance:-100
*/

/* after synchronized:
balance:800
balance:600
balance:400
balance:200
balance:200
balance:200
balance:0
balance:0
*/